//index.js
//获取应用实例
const app = getApp()
const aesjs = require('../../utils/aes.js')

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  clickMe: function() {
    this.setData({motto:"Clicked"})
  },
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getLongitude: function() {
    wx.getLocation({
      success: function(res) {
        var longitude = res.longitude
      },
    })
  },
  getLatitude: function() {

  },
  getExtendParams: function() {
    var random = '';
    for(var i=0;i<4;i++) {
      random += '' + Math.floor(Math.random() * 10);
    }
    var date = new Date();
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    const formatNumber = n => {
      n = n.toString()
      return n[1] ? n : '0' + n
    }
    var formatDate = '' + [year, month, day, hour, minute, second].map(formatNumber).join('');
    
    var jsonData = ',' + formatDate + ',' + random;
    console.log(jsonData)
    var key = aesjs.enc.Utf8.parse('TJWDMALL2017');
    console.log(key.toString());
    var iv = aesjs.enc.Utf8.parse('ponmlkgihgfedcba');
    var srcs = aesjs.enc.Utf8.parse(jsonData);
    var encrypted = aesjs.AES.encrypt(jsonData, key, { iv: iv, mode: aesjs.mode.CBC, padding: aesjs.pad.Pkcs7 });

    console.log(encrypted.toString())
    return encrypted.toString();
  },

  testRequest: function() {
    wx.request({
      url: 'http://www.weldone.shop/interfaces/app/getAds',
      data: {
        adPosition:'51',
        origin:'A011000',
        extend:this.getExtendParams()
      },
      method: 'POST',
      success: function(res) {
        console.log(res.data)
      }
    })
  }
  
})
 